package com.yeskery.nut.webhook.websocket;

import com.yeskery.nut.annotation.bean.Autowired;
import com.yeskery.nut.annotation.websocket.*;
import com.yeskery.nut.webhook.biz.WebHookBiz;
import com.yeskery.nut.websocket.Session;

import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Web Hook websocket 端点
 * @author sprout
 * @version 1.0
 * 2023-06-03 11:12
 */
@WebSocket(path = "/ws/webhook/session/{sessionId}")
public class WebHookWebsocketEndpoint {

    private static final Logger logger = Logger.getLogger(WebHookWebsocketEndpoint.class.getName());

    @Autowired
    private WebHookBiz webHookBiz;

    @OnOpen
    public void onOpen(Session session, @PathParam("sessionId") String sessionId) {
        webHookBiz.registerWebsocketSession(sessionId, session);
        logger.info("会话开启，会话id:" + session.getId() + "，sessionId:" + sessionId);
    }

    @OnClose
    public void onClose(Session session) {
        webHookBiz.closeWebsocketSession(session);
        logger.info("关闭连接" + session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("会话id:" + session.getId() + "收到文本消息:" + message);
    }

    @OnMessage
    public void onMessage(byte[] bytes, Session session) {
        logger.info("会话id:" + session.getId() + "收到二进制消息:" + new String(bytes, StandardCharsets.UTF_8));
    }

    @OnError
    public void onError(Session session, Exception e) {
        webHookBiz.closeWebsocketSession(session);
        logger.logp(Level.SEVERE, WebHookWebsocketEndpoint.class.getName(), "onError",
                "会话发生错误，会话id:" + session.getId(), e);
    }
}
